package com.ruoyi.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.entity.User;
import com.ruoyi.web.domain.user.vo.LoginVo;
import com.ruoyi.web.domain.user.vo.RegisterVo;
import com.ruoyi.web.domain.user.vo.SubscribeVo;
import com.ruoyi.web.entity.user.response.UserCenterResponse;
import com.ruoyi.web.mapper.ApiUserMapper;
import com.ruoyi.web.service.ApiUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class ApiUserServiceImpl implements ApiUserService
{
    private static final Logger logger = LoggerFactory.getLogger(ApiUserServiceImpl.class);

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private ApiUserMapper apiUserMapper;

    @Override
    public UserCenterResponse login(LoginVo loginVo) {
        User user = selectUserBy(loginVo);
        UserCenterResponse response = new UserCenterResponse();
        response.setUser(user);
        return response;
    }

    @Override
    public User selectUserBy(LoginVo loginVo) {
        return apiUserMapper.loginByBase(loginVo);
    }


    @Override
    public UserCenterResponse register(RegisterVo param) {

        // 查询是否已注册
        // TODO 看一下这里代码怎么变成动态的, 就不用每次new了
        LoginVo loginVo = new LoginVo();
        loginVo.setPhoneNumber(param.getPhone());
        UserCenterResponse poaUser = login(loginVo);
        if (poaUser.getUser() != null) {
            return poaUser;
        }

        // 根据手机号,昵称,头像注册
        String openId = "";
        if (param.getType().equals(1)) {
            openId = getUserOpenId(param.getCode());
            if (StringUtils.isBlank(openId)) {
                throw new ServiceException("openId获取失败");
            }
        }

        // 注册
        User register = new User();
        register.setNickName(RandomUtil.randomString(12));
//        register.setPhoto(param.getPhoto());
        register.setPhoneNumber(param.getPhone());
        register.setUuid(openId);

        Integer poaUser1 = apiUserMapper.insert(register);

        if (poaUser1 < 0) {
            throw new ServiceException("用户注册失败");
        }

        return login(loginVo);
    }

    public String getUserOpenId(String code) {

        if (StringUtils.isBlank(code)) {
            throw new ServiceException("缺少code参数");
        }

//        List<WxMaProperties.Config> configs = properties.getConfigs();

//        String appid = configs.get(0).getAppid();

//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }

        String openId = "ddd";
        try {
            if (RuoYiConfig.hasTestPrefix(code)) {
                openId = "wx_test_openId_" + code;
            } else {
                WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
                logger.info(session.getOpenid());
                // 可以增加自己的逻辑，关联业务相关数据
                openId = session.getOpenid();
            }
        } catch (WxErrorException e) {
             e.getError().getErrorMsg();
            throw new ServiceException("获取code超时");
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }

        return openId;
    }

    @Override
    public WxMaPhoneNumberInfo getPhone(String code) {

        WxMaPhoneNumberInfo newPhoneNoInfo = null;
        try {
            newPhoneNoInfo = wxMaService.getUserService().getNewPhoneNoInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return newPhoneNoInfo;
    }

    @Override
    public void sendSubscribe(SubscribeVo subscribeVo) {
        /*
            活动开始提醒
            推送人群：已报名用户
            推送时间：活动开始前10分钟
         */
        List<String> openList = new ArrayList<>();
        openList.add("openId");// TODO 获取用户id openId
        HashMap<String, String> map = new HashMap<>();

        // 当前时间
        DateTime date = DateUtil.date();
        // 格式化日期输出
        String dateFormat = DateUtil.format(date, "yyyy-MM-dd HH:mm");
        // 加入参数
        map.put("thing1", "\uD83D\uDC96️直球式恋爱圆桌");
        map.put("thing2", "\uD83C\uDF1F线上");
        map.put("date3", dateFormat);
        map.put("thing4", "\uD83D\uDD14圆桌活动已开始入场，点击进入活动~");
        map.put("thing5", "10分钟");


        for (String open : openList) {
            getMsgData(open, subscribeVo, map);
        }
    }

    public void getMsgData(String openId, SubscribeVo subscribeVo , HashMap<String, String> map){
        WxMaSubscribeMessage dqwe = new WxMaSubscribeMessage();
        dqwe.setTemplateId(subscribeVo.getTemplateId());
        dqwe.setToUser(openId);
        ArrayList<WxMaSubscribeMessage.MsgData> msgData = new ArrayList<>();


        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            msgData.add(new WxMaSubscribeMessage.MsgData(next.getKey(), next.getValue()));

        }

        dqwe.setData(msgData);
        dqwe.setPage(subscribeVo.getPage());
        dqwe.setMiniprogramState(subscribeVo.getVersion());


//        try {
//            wxMaService.getSubscribeService().sendSubscribeMsg(dqwe);
            System.out.println("发送消息");
//        } catch (WxErrorException e) {
//            System.out.println(e.getError().getErrorCode());
//            System.out.println(e.getError().getErrorMsg());
//            System.out.println(e.getError());
//            throw new ServiceException(e.getError().getErrorMsg(), ConvertUtils.toInt(e.getError().getErrorCode()));
//        }

    }

}
